package com.wdc.deliveryrobot.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.JsonReader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirui.selfstudysdk.main.SelfChassisState;
import com.wdc.deliveryrobot.R;
import com.wdc.deliveryrobot.activity.BaseActivity;
import com.wdc.deliveryrobot.activity.MapActivity;
import com.wdc.deliveryrobot.adapter.LocationAdapter;
import com.wdc.deliveryrobot.adapter.MapAdapter;
import com.wdc.deliveryrobot.decoration.SpaceItemDecoration;
import com.wdc.deliveryrobot.dialog.HintDialog;
import com.wdc.deliveryrobot.view.MapView;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

public class MapFragment extends Fragment implements MapAdapter.OnItemClickListener{

    private SelfChassisState selfChassisState;

    private MapView mapView;

    private Button button;

    private HintDialog hintDialog;

    private Handler handler = new Handler();
    
    private TextView textView;
    private RecyclerView recyclerView;

    private ImageView imageView;

    private boolean isRunning = true;

    private static String TAG  = "mapFragment";

//    private Runnable runnable = new Runnable() {
//        @Override
//        public void run() {
//
//            JSONObject jsonObjectStations = selfChassisState.getStations();
//            JSONArray jsonArrayPoint = jsonObjectStations.getJSONArray("point");
//            if (jsonArrayPoint != null){
//                for (int i = jsonArrayPoint.size() - 1;i >= 0;i --){
//                    if (!jsonArrayPoint.getJSONObject(i).getString("mapName").equals(selfChassisState.getMapName())){
//                        jsonArrayPoint.remove(i);
//                    }
//                }
//            }
//            JSONObject jsonObjectScan = selfChassisState.scan;
//            mapView.setLaserData(selfChassisState.getMapData(),selfChassisState.getChargingPosition(),jsonArrayPoint,jsonObjectScan,mapView.getWidth(),mapView.getHeight());
//            if (isRunning)
//                handler.postDelayed(runnable,1000);
//        }
//    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 加载 Fragment 的布局
        View view = inflater.inflate(R.layout.fragment_map, container, false);
//        mapView = view.findViewById(R.id.mapView);
//        mapView.setBackgroundColor(Color.LTGRAY);
        button = view.findViewById(R.id.openMap);
        recyclerView = view.findViewById(R.id.mapRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new SpaceItemDecoration(5));
        imageView = view.findViewById(R.id.map_src);

        Bitmap decodedBitmap = decodeBase64ToBitmap(selfChassisState.mapData.getData());

        // 设置解码后的 Bitmap 到 ImageView
        imageView.setImageBitmap(decodedBitmap);

        List<String> maplist = new ArrayList<>();
        JSONArray jsonArrayMap = selfChassisState.getMapList();
        if (jsonArrayMap != null && jsonArrayMap.size() > 0){
            for (int i = 0;i < jsonArrayMap.size();i ++){
                maplist.add(jsonArrayMap.get(i).toString());
            }
        }else {
            maplist.add("test.yaml");
        }


        MapAdapter mapAdapter = new MapAdapter(maplist,getContext(),selfChassisState.getMapName(),this);
        recyclerView.setAdapter(mapAdapter);

        textView = view.findViewById(R.id.map_name);
        textView.setText(getString(R.string.map_name,selfChassisState.getMapName().replace(".yaml","")));
        handler = new Handler();
        hintDialog = new HintDialog(getContext());

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               hintDialog.setMessage(getString(R.string.ok_open_map));
               hintDialog.setOkButtonClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {

                       Intent intent = new Intent(getActivity(), MapActivity.class);
                       startActivity(intent);
                   }
               });
               hintDialog.setCancelButtonClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       hintDialog.dismiss();
                   }
               });
               hintDialog.show();
            }
        });


        return view;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof BaseActivity) {
            selfChassisState = ((BaseActivity) context).selfChassisState;
        }
    }


    @Override
    public void onPause() {
        super.onPause();
    }

    private Bitmap decodeBase64ToBitmap(String base64String) {

        String base64Image = base64String.split(",")[1];

        // 解码 Base64 字符串
        byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);

        // 将字节数组转换为 Bitmap
        return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }

    @Override
    public void onItemClick(String location) {
        //获取到地图
        Log.d("thd_","地图名称:" + location + " 开始切换地图");

        new Thread(() -> {
            boolean success = selfChassisState.enterMapNavigation(location);
            if (success){
                Log.d("thd_","成功");
                refreshFragment();
                onResume();
            }else {
                Log.d("thd_","失败");
            }
        }).start();
    }

    private void refreshFragment() {
        // 获取当前的FragmentManager
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();

        // 移除当前的Fragment
        transaction.remove(MapFragment.this);

        // 重新添加MapFragment（这相当于重新加载Fragment）
        transaction.replace(R.id.fragment_container, new MapFragment()); // 这里的R.id.fragment_container是容器ID，需要根据实际情况修改
        transaction.addToBackStack(null); // 如果需要可以添加到Back Stack，避免返回时移除

        // 提交事务
        transaction.commit();
    }
}